package com.stp.queue.test;

public class ArrayQueue {
    private int[] queue;  // 内部数组
    private int front;    // 队列头部指针
    private int rear;     // 队列尾部指针
    private int size;     // 队列当前元素个数
    private int capacity; // 队列容量

    public ArrayQueue(int capacity) {
        this.capacity = capacity;
        queue = new int[capacity];
        front = 0;
        rear = -1;
        size = 0;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == capacity;
    }

    public int size() {
        return size;
    }

    /**
     * 入队操作
     * @param item
     */
    public void enqueue(int item) {
        if (isFull()) {
            System.out.println("Queue is full. Cannot enqueue.");
            return;
        }
        rear = (rear + 1) % capacity; // 循环队列，计算新的尾部位置
        queue[rear] = item;
        size++;
        System.out.println("Enqueued: " + item);
    }

    /**
     * 出队操作
     * @return
     */
    public int dequeue() {
        if (isEmpty()) {
            System.out.println("Queue is empty. Cannot dequeue.");
            return -1;
        }
        int item = queue[front];
        front = (front + 1) % capacity; // 循环队列，计算新的头部位置
        size--;
        System.out.println("Dequeued: " + item);
        return item;
    }

    /**
     * 获取头
     * @return
     */
    public int peek() {
        if (isEmpty()) {
            System.out.println("Queue is empty.");
            return -1;
        }
        return queue[front];
    }

    /**
     * 打印输出
     */
    public void display() {
        if (isEmpty()) {
            System.out.println("Queue is empty.");
            return;
        }
        System.out.print("Queue: ");
        int index = front;
        for (int i = 0; i < size; i++) {
            System.out.print(queue[index] + " ");
            index = (index + 1) % capacity; // 循环遍历队列
        }
        System.out.println();
    }
}
